﻿using System;
using System.IO;
using System.Web;
using log4net;
using System.Collections;

namespace Web.handler
{
    /// <summary>
    /// this class is responsible for WSDL and WSIL downloading. All requests to this resources are handled by this class so that is easily to logs, manipulate and debug.
    /// </summary>
    public class WSDLHandler : IHttpHandler
    {
        
        private static readonly ILog log = LogManager.GetLogger(typeof(WSDLHandler));
        private Hashtable wsStore = null;
        
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }
        
        public void ProcessRequest(HttpContext context)
        {

            wsStore =  (Hashtable) context.Application.Get("wsStore");
            
            
            log.Debug("new request for WSDL");
            HttpContext current = HttpContext.Current;
            int position = current.Request.FilePath.LastIndexOf('/');
            //int lenght = current.Request.FilePath.Length;
            string file = current.Request.FilePath.Substring(position+1);
            
            
            log.Error("filepath " + current.Request.FilePath);
            string path = current.Server.MapPath("~/wsdl/" + file);
            fillWSDLResponse(path , context);
            log.Debug("wsdl created");
            // end of processing
            return;       

        }

        #endregion


        /// <summary>
        /// This method takes a file and all its data puts do the context.response
        /// 
        /// </summary>
        /// <param name="filePath">absolute path to the file</param>
        /// <param name="context"></param>
        /// <example>
        ///     <code>fillWSDLResponse(HttpContext.Current.Server.MapPath("~/App_Data")+"/Calculator.wsdl",context);</code>
        /// </example>
        public void fillWSDLResponse(String filePath, HttpContext context)
        {
            context.Response.ContentType = "text/xml";
            log.Debug("reading wsdl from path "+filePath);
            FileStream wsdlStream = File.OpenRead(filePath);
            int buffSize = 1;
            byte[] buff = new byte[buffSize];
            int bytes = 0;
            while ( (bytes = wsdlStream.Read(buff, 0, buffSize)) > 0)
            {
                context.Response.OutputStream.Write(buff, 0, buffSize);
            }
            
            context.Response.OutputStream.Flush();

        }


    }

    }

